import { loginApi, picimgApi } from '@/api/user'
const state = {
  userList: {},
  clientToken: null,
  lowTime: 0,
  token: null
}

const mutations = {
  setList(state, userList) {
    state.userList = userList
  },
  removeList(state) {
    state.userList = {}
  },
  setClient(state, clientToken) {
    state.clientToken = clientToken
  },
  removeClient(state) {
    state.clientToken = null
  },
  setToken(state, token) {
    state.token = token
  },
  removeToken(state) {
    state.token = null
  },
  updatedTime(state, time) {
    state.lowTime = time
  }
}

const actions = {
  async loginAction(context, data) {
    const res = await loginApi(data)
    console.log(res)
    context.commit('setList', res)
    context.commit('setToken', res.token)
    context.commit('updatedTime', Date.now())
  },
  async picimgAction(context, data) {
    const res = await picimgApi(data)
    context.commit('setClient', data)
    const bufferUrl = btoa(
      new Uint8Array(res).reduce(
        (data, byte) => data + String.fromCharCode(byte),
        ''
      )
    )
    return 'data:image/png;base64,' + bufferUrl
  },
  tologinAction({ commit }) {
    commit('removeList')
    commit('removeToken')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
